package com.logistics.pick.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistics.dictionary.entity.model.DictionaryRow;
import com.logistics.dictionary.service.DictionaryService;
import com.logistics.erp.entity.domain.ErpInvReq;
import com.logistics.inventory.entity.domain.Inventory;
import com.logistics.inventory.service.InventoryService;
import com.logistics.map.entity.domain.MapComponents;
import com.logistics.map.service.MapComponentsService;
import com.logistics.pick.entity.domain.*;
import com.logistics.pick.entity.model.PickDetailInfoRow;
import com.logistics.pick.entity.model.PickDetailRow;
import com.logistics.pick.entity.model.PickQuery;
import com.logistics.pick.mapper.PickDetailMapper;
import com.logistics.utils.bean.ResultPager;
import com.logistics.utils.constants.Constants;
import com.logistics.utils.exception.MessageException;
import com.logistics.utils.tool.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 拣配明细 服务实现类
 * </p>
 *
 * @author yunjian.ban
 * @since 2024-06-28
 */
@Service
public class PickDetailService extends ServiceImpl<PickDetailMapper, PickDetail> {

    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private PickDetailMapper pickDetailMapper;
    @Autowired
    private MapComponentsService mapComponentsService;

    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 根据站点判断是否需要空托并查询站点物料明细
     * @param station
     * @return
     * @throws MessageException
     */
    public Map<String,Object> findStationPickList(String station) throws MessageException {
        Map<String,Object> map = new HashMap<>();
        List<Map> pickDetailList = new ArrayList<>();
        Inventory inventory = inventoryService.getOne(new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getStation, station));
        MapComponents mapComponents = mapComponentsService.getOne(new LambdaQueryWrapper<MapComponents>()
                .eq(MapComponents::getLocation,station)
                .eq(MapComponents::getLocationLock,Constants.LOCATION_RELEASE));
        //判断是否需要空托
        if (StringUtils.isNull(inventory)&&StringUtils.isNotNull(mapComponents)) {
            map.put("emptyCall",true);
        }else{
            pickDetailList =  pickDetailMapper.findStationPickList(station);
            System.out.println(pickDetailList);
            map.put("emptyCall",false);
            map.put("container",inventory.getContainer());
        }
        map.put("materialList",pickDetailList);

        return map;
    }

    /**
     * 根据拣配单查找出没完成拣配的物料
     *
     * @param pickId
     * @param container
     * @return
     */
    public List<PickDetailRow> listByPickId(String pickId, String container) {
        return pickDetailMapper.findByPickId(pickId, container).stream().map(PickDetailRow::build).
                collect(Collectors.toList());
    }

    /**
     * 根据退库单查找出已经绑定的物料
     * @param reqNo
     * @return
     */
    public List<ErpInvReq> MaterialReturnByReqNo(String reqNo) {
        return pickDetailMapper.findMaterialReturnByReqNo(reqNo);
    }

    /**
     * 查找物料信息
     * @param itemCode
     * @param itemWorkCode
     * @param itemOpNo
     * @return
     */
    public PickDetail pickDetail(String itemCode, String itemWorkCode, String itemOpNo){
        Map<String,Object> param = new HashMap<>();
        param.put("itemCode",itemCode);
        param.put("itemWorkCode",itemWorkCode);
        param.put("itemOpNo",itemOpNo);
        return pickDetailMapper.findPickDetail(param);
    }

    /**
     * 查找拣配数量
     * @param billNo
     * @param itemCode
     * @param orderNo
     * @param itemOpNo
     * @return
     */
    public BigDecimal totalPickQty(String billNo, String orderNo, String itemCode,  String itemOpNo, String seqNo){
        Map<String,Object> param = new HashMap<>();
        param.put("billNo",billNo);
        param.put("itemCode",itemCode);
        param.put("orderNo",orderNo);
        param.put("itemOpNo",itemOpNo);
        param.put("seqNo",seqNo);
        return pickDetailMapper.findTotalPickQty(param);
    }

    /**
     * 根据 拣配单ID查找拣配详细信息
     * @param param
     * @return
     */
    public ResultPager getPickDetailInfoByPickId(PickQuery param) throws MessageException {
        //判断是否分页
        if(StringUtils.isNotNull(param.getPageSize())){
            IPage page = new Page(param.getCurrent(), param.getPageSize());
            param.setPage((int) page.offset());
        }
        //获取查询数据
        List<PickAndErpInvbill> pickAndErpInvbills = pickDetailMapper.findPickDetailInfoByPickId(param);
        //获取查询数据总条数
        param.setPage(0);
        long pickAndErpInvbillCount = pickDetailMapper.findPickDetailInfoByPickId(param).stream().count();
        //
        //获取拣配单状态dictionary
        Map<String, String> statusMap = dictionaryService.getChildrenByCode("pick_status_type")
                .stream().collect(Collectors.toMap(DictionaryRow::getCode, DictionaryRow::getName));
        //获取缺料状态dictionary
        Map<String, String> lackMaterialStatusMap = dictionaryService.getChildrenByCode("lack_material_status")
                .stream().collect(Collectors.toMap(DictionaryRow::getCode, DictionaryRow::getName));
        //获取erp单据类型dictionary
        Map<String, String> erpInvbillTypeMap = dictionaryService.getChildrenByCode("erp_invbill_type")
                .stream().collect(Collectors.toMap(DictionaryRow::getCode, DictionaryRow::getName));
        //set 描述信息
        List<PickDetailInfoRow> result =
                pickAndErpInvbills.stream().map(item -> PickDetailInfoRow.build(item) ).collect(Collectors.toList())
                        .stream().map(item -> {
                    item.setStatusName(statusMap.get(item.getStatus()));
                    item.setLackMaterialStatusName(lackMaterialStatusMap.get(item.getLackMaterialStatus().toString()));
                    item.setErpInvbillTypeName(erpInvbillTypeMap.get(item.getErpInvbillType().toString()));
                    return item;
                }).collect(Collectors.toList());
        return new ResultPager(result, (int) pickAndErpInvbillCount);
    }
    /**
     * 根据托盘号查找物料编号
     * @param param
     * @return
     */
    public List<PickDetailInvBill> materials(PickDetailInvBill param){
        return pickDetailMapper.findMaterials(param);
    }


    /**
     * 根据托盘id查找优先级
     * @param containerId
     * @return
     */
    public Integer isPriority(String containerId){
        return pickDetailMapper.findIsPriority(containerId);
    }

    /**
     * 查找已拣配数量
     * @param pickId
     * @return
     */
    public List<PickQty> pickQty(String pickId){
        return pickDetailMapper.findPickQty(pickId);
    }

    /**
     * 查找非立体库拣配数量
     * @param pickId
     * @return
     */
    public List<PickQty> pickQtyGroupBySeq(String pickId){
        return pickDetailMapper.findPickQtyGroupBySeq(pickId);
    }

    /**
     * 查找装配班组的拣配单是否配送过
     * @param pickId
     * @return
     */
    public Integer findAssemblyByBillNo(Integer pickId){
        return pickDetailMapper.findAssemblyByBillNo(pickId);
    }
}
